package org.sang.utils;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MD5Util {

    static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    static  String MD5 = "MD5";

    public static String sign(String data, String key) throws Exception{
        // 得到明文的字节数组
        byte[] btInput = (data+key).getBytes();
        // 创建一个提供信息摘要算法的的对象（MD5摘要算法）
        MessageDigest messageDigest = MessageDigest.getInstance(MD5);
        // 使用指定的字节更摘要
        messageDigest.update(btInput);
        // 得到二进制密文
        byte[] encryptData = messageDigest.digest();
        // 把密文转换成十六进制的字符串形式
        return bytesToHex(encryptData);
    }

    public static String bytesToHex(byte[] bytes){
        int k = 0;
        char[] hexChars = new char[bytes.length*2];
        for(int i=0; i<bytes.length; i++){
            byte byte0 = bytes[i];
            hexChars[k++] = hexDigits[byte0 >>> 4 & 0xf];
            hexChars[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(hexChars);
    }

    public static  boolean verifySign(String data, String key, String sign) throws Exception {
        // 调用加签方法，对比加签后的签名是否一致
        String encryptData = sign(data, key);
        return encryptData.equals(sign);
    }

    public static void main(String[] args) throws Exception {
        String data = "{ \n" +
                "\"trade_no\":\"192376547821987234\", \n" +
                "\"mch_id\": \"180212110446000000\", \n"+
                "\"bank_card_no\": \"622**********123\", \n" +
                "\"name\": \"苏**\",  \n" +
                "\"phone\": \"188********\",  \n" +
                "\"expire_data\": \"2901\", \n" +
                "\"cvn2\": \"123\", \n" +
                "\"trade_amount\": \"100\", \n" +
                "\"trade_desc\": \"牙膏\", \n" +
                "\"currency_code\": \"CNY\", \n" +
         "}";
        String sign = "C9F6D25A07EE1709EAA7F644CAAC131F";
        String key = "abc123456";
        String calcSign = sign(data, key);
        System.out.println("calcSign="+calcSign);
        System.out.println(verifySign(data, key, sign));
    }

    public static String sortMap(Map<String,?> maps){
        TreeMap<String, Object> treeMap = new TreeMap<>();
        for(Map.Entry<String, ?> map: maps.entrySet()){
            Object value  = map.getValue();
            if(value!=null){
                treeMap.put(map.getKey(), value);
            }
        }
        // 遍历 treeMap 并生成签名data
        Iterator<String> iterator = treeMap.keySet().iterator();
        StringBuilder sortData = new StringBuilder();
        while (iterator.hasNext()){
            String key = iterator.next();
            String value = (String) treeMap.get(key);
            sortData.append(key).append("=").append(value);
            if(iterator.hasNext()){
                sortData.append("&");
            }
        }
        return sortData.toString();
    }
}
